package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import Models.PitchNotes;

public class PitchNotesPresenter extends AbstractPresenter<PitchNotes> {
	final String SINGLEITEM = "pitchNotes";
	final String MULTIITEM = "pitchNotess";
	
	public ArrayList<PitchNotes> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public PitchNotes tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public PitchNotes createItemFromJSONObject(JSONObject jsonObject){
		PitchNotes item = new PitchNotes();
		try{
			item.setId(jsonObject.getInt("pitchNoteID"));
			item.setNotes(jsonObject.getString("notes"));
			item.setPitchTime(timeFormat.parse(jsonObject.getString("pitchTime")));
			item.setPitchType(jsonObject.getInt("pitchType"));
			item.setPitchVolume(jsonObject.getDouble("volPitched"));
			
			if(!jsonObject.isNull("yeastID")){
				//create product if set
				YeastViewPresenter presenter = new YeastViewPresenter();
				JSONObject jsonGroup = jsonObject.getJSONObject("yeastID");
				item.setYeast(presenter.createItemFromJSONObject(jsonGroup));
			} else {
				item.setYeast(null);
			}
			
			if(!jsonObject.isNull("yeastGenId")){
				//create product if set
				YeastGenPresenter presenter = new YeastGenPresenter();
				JSONObject jsonGroup = jsonObject.getJSONObject("yeastGenId");
				item.setYeastGeneration(presenter.createItemFromJSONObject(jsonGroup));
			} else {
				item.setYeastGeneration(null);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(PitchNotes item){
		try{
			JSONObject json = new JSONObject();

			json.put("pitchNoteID", item.getId());
			json.put("notes", item.getNotes());
			json.put("pitchTime", getDate(item.getPitchTime()));
			json.put("pitchType", item.getPitchType());
			json.put("volPitched", item.getPitchVolume());

			if(item.getYeast()!=null){
				final YeastViewPresenter presenter = new YeastViewPresenter();
				json.put("yeastID", presenter.createJSON(item.getYeast()));
			} else {
				json.put("yeastID", JSONObject.NULL);
			}

			if(item.getYeastGeneration()!=null){
				final YeastGenPresenter presenter = new YeastGenPresenter();
				json.put("yeastGenId", presenter.createJSON(item.getYeastGeneration()));
			} else {
				json.put("yeastGenId", JSONObject.NULL);
			}
			
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public PitchNotes getEmptyEntity(){
		PitchNotes entity = new PitchNotes();
		return entity;
	}
}
